import xml.etree.ElementTree as ET
import xmltodict
import json

def xml_to_json(xml_str):
    # parse是的xml解析器
    xml_parse = xmltodict.parse(xml_str,encoding="UTF-8")
    # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
    # dumps()方法的ident=1,格式化json
    json_str = json.dumps(xml_parse,ensure_ascii= False,indent=1)
    f2 = open('demo_json.json', 'w')
    f2.write(json_str)
    f2.close()
    # return json_str


def xmltojson(xmlstr):
    # parse是的xml解析器
    print("heihe")
    xmlparse = xmltodict.parse(xmlstr)
    # json库dumps()是将dict转化成json格式，loads()是将json转化成dict格式。
    # dumps()方法的ident=1，格式化json
    jsonstr = json.dumps(xmlparse, indent=1)
    print("执行到这了")
    print(jsonstr)
# 学习用ET获取xml内容
tree = ET.parse('demo.xml')
root = tree.getroot()
nroot = ET.Element("data")
for child in root.iter("Event"):
    print(child.tag, child.attrib)
    Event = ET.SubElement(nroot, 'Event', child.attrib)

    for son in child:
        Str = son.text
        print(son.tag, Str)
        th = ET.SubElement(Event, son.tag)
        th.text = Str
ntree = ET.ElementTree(nroot)
ntree.write("ntree.xml", encoding="UTF-8")
print("=====================")
xml_to_json(ET.tostring(nroot,encoding="UTF-8"))